import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { getDepartmentList, deleteDepartment, updateDepartment, addDepartment } from '../apis/department'

/**
 * 部门管理相关hook
 */
export function useDepartment() {
  // 加载状态
  const loading = ref(false)

  // 搜索表单
  const searchForm = reactive({
    deptName: '',
    deptCode: '',
    status: ''
  })

  // 部门列表数据
  const departmentList = ref([])

  // 分页信息
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // 查看对话框
  const viewDialogVisible = ref(false)
  const viewForm = reactive({})

  // 格式化货币
  const formatCurrency = (row, column, cellValue) => {
    if (cellValue === null || cellValue === undefined || cellValue === '') {
      return '¥0.00'
    }
    return '¥' + Number(cellValue).toFixed(2)
  }

  // 格式化状态
  const formatStatus = (row, column, cellValue) => {
    return cellValue === 1 ? '启用' : '禁用'
  }

  // 获取部门列表
  const loadDepartments = async () => {
    loading.value = true
    try {


      // 调用真实API
      const response = await getDepartmentList({
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        deptName: searchForm.deptName,
        deptCode: searchForm.deptCode,
        status: searchForm.status
      })
      
      if (response.code === 200) {
        departmentList.value = response.data.records || []
        pagination.total = response.data.total || 0
      } else {
        ElMessage.error(response.message || '获取部门列表失败')
      }
    } catch (error) {
      console.error('获取部门列表异常:', error)
      ElMessage.error('获取部门列表失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.currentPage = 1
    loadDepartments()
  }

  // 重置搜索
  const resetSearch = () => {
    searchForm.deptName = ''
    searchForm.deptCode = ''
    searchForm.status = ''
    pagination.currentPage = 1
    loadDepartments()
  }

  // 分页大小改变
  const handleSizeChange = (size) => {
    pagination.pageSize = size
    loadDepartments()
  }

  // 当前页码改变
  const handleCurrentChange = (current) => {
    pagination.currentPage = current
    loadDepartments()
  }

  // 选择行变化
  const handleSelectionChange = (selection) => {
    // 暂不实现批量删除功能
  }

  // 编辑对话框
  const editDialogVisible = ref(false)
  const editForm = reactive({})
  const editLoading = ref(false)
  
  // 新增对话框
  const addDialogVisible = ref(false)
  const addForm = reactive({
    deptName: '',
    deptCode: '',
    parentId: null,
    managerId: null,
    costCenter: '',
    budgetAmount: 0,
    status: 1,
    sortOrder: 0
  })
  const addLoading = ref(false)

  // 编辑部门
  const handleEdit = (row) => {
    Object.assign(editForm, row)
    editDialogVisible.value = true
  }
  
  // 打开新增部门对话框
  const handleAdd = () => {
    // 重置表单
    Object.assign(addForm, {
      deptName: '',
      deptCode: '',
      parentId: null,
      managerId: null,
      costCenter: '',
      budgetAmount: 0,
      status: 1,
      sortOrder: 0
    })
    addDialogVisible.value = true
  }

  // 查看部门详情
  const handleView = (row) => {
    Object.assign(viewForm, row)
    viewDialogVisible.value = true
  }

  // 保存编辑
  const saveEdit = async () => {
    editLoading.value = true
    try {
      const response = await updateDepartment(editForm.id, editForm)
      if (response.code === 200) {
        ElMessage.success('编辑成功')
        editDialogVisible.value = false
        loadDepartments()
      } else {
        ElMessage.error(response.message || '编辑失败')
      }
    } catch (error) {
      console.error('编辑部门异常:', error)
      ElMessage.error('编辑失败，请稍后重试')
    } finally {
      editLoading.value = false
    }
  }
  
  // 保存新增部门
  const saveAdd = async () => {
    addLoading.value = true
    try {
      const response = await addDepartment(addForm)
      if (response.code === 200) {
        ElMessage.success('新增部门成功')
        addDialogVisible.value = false
        loadDepartments()
      } else {
        ElMessage.error(response.message || '新增失败')
      }
    } catch (error) {
      console.error('新增部门异常:', error)
      ElMessage.error('新增失败，请稍后重试')
    } finally {
      addLoading.value = false
    }
  }

  // 删除部门
  const handleDelete = async (id) => {
    try {
      const response = await deleteDepartment(id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadDepartments()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除部门异常:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }

  // 返回所有需要的变量和方法
  return {
    loading,
    searchForm,
    departmentList,
    pagination,
    viewDialogVisible,
    viewForm,
    editDialogVisible,
    editForm,
    editLoading,
    addDialogVisible,
    addForm,
    addLoading,
    formatCurrency,
    formatStatus,
    loadDepartments,
    handleSearch,
    resetSearch,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleEdit,
    handleDelete,
    handleView,
    saveEdit,
    handleAdd,
    saveAdd
  }
}